<template>
  <div class="edit-refund">
    <v-dialog title="收回押金" :show.sync="dialogVisible" width="1200px" @beforeClose="beforeClose">
      <div class="card-box">
        <el-form ref="editForm" :model="form" size="small" :rules="rules">
          <div class="form-wrap">
            <el-form-item label="物业名称" prop="propertyNames">
              <el-input disabled v-model="form.propertyNames"></el-input>
            </el-form-item>
            <el-form-item label="出租方" prop="customerName">
              <el-input disabled v-model="form.customerName"></el-input>
            </el-form-item>
            <el-form-item label="收据编码">
              <el-input v-model="form.dataCode"></el-input>
            </el-form-item>
            <el-form-item label="收款银行" prop="bankName">
              <el-input v-model="form.bankName" placeholder="请输入收款银行"></el-input>
            </el-form-item>
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="form.bankAccount" placeholder="请输入银行账号"></el-input>
            </el-form-item>
            <el-form-item label="收款人姓名" prop="collectionName">
              <el-input v-model="form.collectionName" placeholder="请输入收款人姓名"></el-input>
            </el-form-item>
            <el-form-item label="操作日期" prop="operationDate">
              <el-date-picker v-model="form.operationDate" type="date" size="small" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="应收日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="操作人员" prop="operationName">
              <el-input disabled v-model="form.operationName" placeholder="请输入操作人员"></el-input>
            </el-form-item>
            <el-form-item label="说明" class="full" prop="remarks">
              <el-input v-model="form.remarks"></el-input>
            </el-form-item>
          </div>
          <el-table :data="tableDataArr" style="width: 100%">
            <el-table-column prop="chargeProjectName" label="收款项目" width="120" align="center"></el-table-column>
            <el-table-column prop="costPeriodStart" label="费用期间" width="260" align="center"></el-table-column>
            <el-table-column prop="collectionAmount" label="已收金额(元)" width="120" align="center"></el-table-column>
            <el-table-column prop="receivableMoney" label="可退金额(元)" width="120" align="center"></el-table-column>
            <el-table-column prop="refundAmount" label="退款金额(元)" width="260" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.refundAmount" placeholder="请输入" @change="handleChange"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <span slot="foot">
        <el-button @click="close">取 消</el-button>
        <el-button v-throttle="[commit]">提 交</el-button>
      </span>
    </v-dialog>
  </div>
</template>

<script>
import { getCollection, addCollectionRefund, getRefundAmountCount } from '../../api/collection'
import BaseLoad from '@/assets/vue-mixin/BaseLoad'

export default {
  name: "edit-refund",
	mixins: [BaseLoad],
  data () {
    let validateBankAccount = (rule, value, callback) => {
      let bankAccount = value.replace(/\s/g, '');
      let num = /^\d*$/;//全数字
      if (!num.exec(bankAccount)) {
        callback("银行账号必须全为数字");
      }
      if (bankAccount.length < 16 || bankAccount.length > 19) {
        callback("银行账号长度必须在16到19之间");
      }
      //开头6位
      let strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
      if (strBin.indexOf(bankAccount.substring(0, 2)) == -1) {
        callback("银行账号开头6位不符合规范");
      }
      let lastNum = value.substr(bankAccount.length - 1, 1);//取出最后一位（与luhn进行比较）

      let first15Num = value.substr(0, bankAccount.length - 1);//前15或18位
      let newArr = new Array();
      for (let i = first15Num.length - 1; i > -1; i--) {    //前15或18位倒序存进数组
        newArr.push(first15Num.substr(i, 1));
      }
      let arrJiShu = new Array();  //奇数位*2的积 <9
      let arrJiShu2 = new Array(); //奇数位*2的积 >9

      let arrOuShu = new Array();  //偶数位数组
      for (let j = 0; j < newArr.length; j++) {
        if ((j + 1) % 2 == 1) {//奇数位
          if (parseInt(newArr[j]) * 2 < 9)
            arrJiShu.push(parseInt(newArr[j]) * 2);
          else
            arrJiShu2.push(parseInt(newArr[j]) * 2);
        } else //偶数位
          arrOuShu.push(newArr[j]);
      }

      let jishu_child1 = new Array();//奇数位*2 >9 的分割之后的数组个位数
      let jishu_child2 = new Array();//奇数位*2 >9 的分割之后的数组十位数
      for (let h = 0; h < arrJiShu2.length; h++) {
        jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
        jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
      }

      let sumJiShu = 0; //奇数位*2 < 9 的数组之和
      let sumOuShu = 0; //偶数位数组之和
      let sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
      let sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
      let sumTotal = 0;
      for (let m = 0; m < arrJiShu.length; m++) {
        sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
      }

      for (let n = 0; n < arrOuShu.length; n++) {
        sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
      }

      for (let p = 0; p < jishu_child1.length; p++) {
        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
      }
      //计算总和
      sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

      //计算luhn值
      let k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
      let luhn = 10 - k;

      if (lastNum == luhn) {
        callback();
      } else {
        callback("银行账号不符合校验规则");
      }
    }
    return {
      dialogVisible: false,
      form: {
        payStatus: '',
        adjustmentType: '',
        chargeProjectName: '',
        dataCode: '',
        propertyNames: '',
        receivableMoney: '',
        customerName: '',
        costPeriodStart: '',
        costPeriodEnd: '',
        receivableDate: '',
        billNumber: '',
        taxAmount: '',
        remarks: '',
        paidType: '',
        costPeriodArr: [],
        refundBatch: '',
        bankName: '',
        bankAccount: '',
        collectionName: '',
        operationDate: '',
        operationName: '',
        refundAmount: '',
        actualId: ''
      },
      tableDataArr: [{
        chargeProjectName: '',
        refundAmount: '',
        receivableMoney: '',
        collectionAmount: '',
        costPeriodStart: ''
      }],
      rules: {
        bankName: [{ required: true, message: '请输入收款银行', trigger: 'blur' }],
        bankAccount: [{ required: true, message: '请输入银行账号', trigger: 'blur' },
        { validator: validateBankAccount, trigger: 'blur' }
        ],
        collectionName: [{ required: true, message: '请输入收款人姓名', trigger: 'blur' }],
        operationDate: [{ required: true, message: '请输入操作日期', trigger: 'blur' }]
      },
    }
  },
  methods: {
    //打开弹框
		async show (item) {
			if (item) {
				this.loadAction('数据加载中，请稍等...')
				this.form = item
				this.form.operationName = item.createName
				Object.keys(this.form).forEach(key => {
					this.form[key] = item[key]
				})
				this.tableDataArr[0].chargeProjectName = this.form.chargeProjectName
				this.tableDataArr[0].refundAmount = this.form.refundAmount
				this.tableDataArr[0].collectionAmount = this.form.collectionAmount
				await getCollection(item.receivableId).then(res => {
					if (res.data.code === 0 && res.data.data !== null) {
						this.tableDataArr[0].costPeriodStart = res.data.data.costPeriodStart + "至" + res.data.data.costPeriodEnd
					}
				})
				await getRefundAmountCount(item.actualId).then(res => {
					if (res.data.code === 0) {
						this.tableDataArr[0].receivableMoney = (Number(this.tableDataArr[0].collectionAmount) - Number(res.data.data)).toFixed(2)
					}
				})
			}
      this.dialogVisible = true
			this.loadClose()
    },
    //关闭弹框
    beforeClose (done) {
      this.$emit('beforeClose')
    },
    //取消
    close () {
      this.$emit('handleClose')
      this.dialogVisible = false
    },
    //提交
    commit () {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.tableDataArr[0].refundAmount === '' || this.tableDataArr[0].refundAmount === undefined || this.tableDataArr[0].refundAmount === null) {
            this.$message.error('退款金额不能为空!')
          } else {
            if (Number(this.tableDataArr[0].refundAmount) > Number(this.tableDataArr[0].receivableMoney)) {
              this.$message.error('退款金额不能大于可退金额!')
            } else {
              if (Number(this.tableDataArr[0].refundAmount) <= 0) {
                this.$message.error('退款金额不能小于或等于0!')
              } else {
                this.form.refundAmount = this.tableDataArr[0].refundAmount
                addCollectionRefund(this.form).then(res => {
                  if (res.data.code === 0) {
                    this.suc('添加成功')
                    this.dialogVisible = false
                    this.$emit('resetList')
                  } else {
                    this.err('添加失败')
                  }
                })
              }
            }
          }
        }
      })
    },
    handleChange (val) {
      let reg = /^(([1-9]\d*)|(0))(\.\d{1,2})?$/;
      if (!reg.test(val)) {
        this.$message.error('退款金额数值格式错误（最多保留两位小数）！')
        this.tableDataArr[0].refundAmount = ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
@include formWrap(4);
</style>
